package com.example.chatweb.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.chatweb.service.PDFService;
import com.example.chatweb.utils.HttpUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <h3>chat-web</h3>
 *
 * @author HuangJiayu
 * @description <p>PDF服务实现类</p>
 * @date 2024-04-05 09:52
 **/
@Service
@Slf4j
public class PDFServiceImpl implements PDFService {
	
	@Autowired
	private HttpUtil httpUtil;
	
	@Override
	public String translate(String prefix, String text) {
		String url = "http://10.112.203.120:8009/translate";
		Map<String, Object> params = new HashMap<>(2);
		params.put("prefix", prefix);
		// 切分字符串，转换为数组。如果字符串大于512则会被截断，优先按照句号(. 。)切分，同时保证每一段都小于512
		List<String> textList = new ArrayList<>();
		if (text.length() > 512) {
			String[] split = text.split("[。.]");
			StringBuilder sb = new StringBuilder();
			for (String s : split) {
				if (sb.length() + s.length() < 512) {
					sb.append(s).append("。");
				} else {
					textList.add(sb.toString());
					sb = new StringBuilder(s).append("。");
				}
			}
			textList.add(sb.toString());
		} else {
			textList.add(text);
		}
		params.put("text", textList);
		JSONObject response = httpUtil.post(url, params);
		JSONArray translations = response.getJSONArray("translation");
		//	拼接为字符串
		StringBuilder res = new StringBuilder();
		for (Object translation : translations) {
			res.append(translation);
		}
		return res.toString();
	}
	
}
